# -*- coding:utf-8 -*-
import os,sys
import re
import traceback
import time
sys.path.append(os.path.join(os.path.abspath(os.path.dirname(__file__)), os.pardir))
import supeanut_config
from CommonLib.mylog import mylog
from CommonLib.db.MongoDBTool import MongoDBTool
from CommonLib.FileTool.CsvTool import CsvTool
from CommonLib.StockTool import StockTool


'''
作者：supeanut
创建时间：2016-xx-xx xx:xx:xx
功能描述：
相关配置：
	supeanut_config.XXX
历史改动：
	2016-xx-xx: xxxxxx
'''
class ExRightsSend:
	# init what
	def __init__(self):
		self.mongo = MongoDBTool()
		self.csvtool = CsvTool()
		self.db_name = supeanut_config.MONGO_DB
		self.csv_path = supeanut_config.EXRIGHTS_DATA_CSV_PATH
		self.stock_obj = StockTool()
		self.coll_exrights = supeanut_config.MONGO_COLL_EXRIGHTS

	# 更新StockInfo 
	def insert(self, ):
		log = mylog('ExrightsSend.upsert', None)
		flag, msg = self.mongo.conn(self.db_name, self.coll_exrights)
		if flag is False:
			log.error(msg)
			return False, msg
		filename_list = os.listdir(self.csv_path)
		for filename in filename_list:
			flag, records = self.csvtool.read_csv(self.csv_path, filename)
			if flag is False:
				log.warning('read file %s failed'%filename)
				return False, 'read file %s failed'%filename
			code = filename
			for record in records:
				doc = {}
				doc['code'] = code
				doc['date'] = record[0].decode('utf-8')
				doc['songgu'] = record[1].decode('utf-8')
				doc['zenggu'] = record[2].decode('utf-8')
				doc['paixi'] = record[3].decode('utf-8')
				doc['peigu'] = record[4].decode('utf-8')
				doc['peigujia'] = record[5].decode('utf-8')
				update_suc = False
				while not update_suc:
					try:
						if self.mongo.coll.find_one({'code':code, 'date':record[0]}) is None:
							self.mongo.coll.insert_one(doc)
						else:
							break
					except:
						flag, msg = self.mongo.conn(self.db_name, self.coll_exrights)
						if flag is False:
							log.error(traceback.format_exc())
							return False, traceback.format_exc()
						else:
							continue
					update_suc = True
		log.info('suc')
		return True, 'suc'

if __name__ == '__main__':
	obj = ExRightsSend()
	print obj.insert()
